package dk.suaq.halfdoneprojects.server;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import dk.suaq.halfdoneprojects.client.GreetingService;
import dk.suaq.halfdoneprojects.server.model.User;
import dk.suaq.halfdoneprojects.shared.FieldVerifier;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
		GreetingService {

	public String greetServer(String input) throws IllegalArgumentException {
		// Verify that the input is valid. 
		if (!FieldVerifier.isValidName(input)) {
			// If the input is not valid, throw an IllegalArgumentException back to
			// the client.
			throw new IllegalArgumentException(
					"Name must be at least 4 characters long");
		}

		UserDao dao = new UserDao();
		User u = dao.get(input); 
		boolean created = false; 
		if (u == null) {
			u = dao.save(new User(input));
			created = true; 
		}
		
		String serverInfo = getServletContext().getServerInfo();
		return "Hello, " + input + "!<br><br>I am running " + serverInfo
				+ " <br>User was created: " + created
				+ " " + u.getUsername();
	}
}
